import React from 'react';
import { ContentPackage, AdvancedSearch, DATA_ENTRY, TableC, ModalC } from '../../../comps';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Checkbox, message, Button } from 'antd';
import { connect } from 'dva';
import moment from 'moment';
import EtfProposalC from '../EtfTradeNew/etfProposal';
let searchPars = {
  proposalWriteDate: moment(new Date()).format('YYYY-MM-DD'),
  proposalType: 'ETF',
};
class ApprovalP extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      checked: true,
      searchParam: null,
      modalVisible: false,
      isReset: false, //是否重置
      selectVal: null,
      rowObj: null,
      loadingRefuse: false,
      loadingOk: false,
      currentUser: {}, //获取用户
    };
  }
  componentDidMount() {
    const { dispatch } = this.props;
    const {
      globalM: {
        dataDictionary: { PROPOSAL_STATUS = [], PROPOSAL_TYPE = [] },
      },
    } = this.props;
    dispatch({
      type: 'proposalVerifyM/valSelect',
      payload: {
        PROPOSAL_STATUS,
        PROPOSAL_TYPE,
      },
    });
    this.getSelect(); //获取下拉框的数据--状态--建议书类型

    this.props.dispatch({
      type: 'etfProposalM/getUserInfo',
      payload: {
        userId: localStorage.getItem('antd-pro-userId'),
      },
      callback: (res) => {
        if (res) {
          this.setState({
            currentUser: res,
          });
        }
      },
    });
  }
  componentWillUnmount() {
    this.timer && clearInterval(this.timer);
  }
  //调用分页的方法
  getDatas = (current, pageSize, searchParams, selectVal) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'proposalVerifyM/getData',
      payload: {
        selectVal,
        currentPage: current,
        numInPage: pageSize,
        ...searchParams,
      },
    });
  };
  //获取下拉框的方法
  getSelect = () => {
    const { dispatch } = this.props;
    const {
      globalM: {
        dataDictionary: { PROPOSAL_STATUS = [], PROPOSAL_TYPE = [] },
      },
    } = this.props;

    let selectVal = {
      PROPOSAL_STATUS,
      PROPOSAL_TYPE,
    };
    this.setState(
      {
        //存储查询table的参数，初始化进行查询
        searchParam: { ...searchPars },
        selectVal: selectVal,
      },
      () => {
        this.getDatas(1, 10, searchPars, selectVal);
        this.timer = setInterval(() => {
          this.getDatas(1, 10, searchPars, selectVal);
        }, 5000);
      },
    );
  };
  //点击查询
  onQuery = (e) => {
    const { pageInfo } = this.props.proposalVerifyM;
    if (!!e.proposalWriteDate) {
      e.proposalWriteDate = e.proposalWriteDate.format('YYYY-MM-DD');
    }
    // e.username = e.username ? e.username.trim():'';
    this.timer && clearInterval(this.timer);
    this.setState(
      {
        searchParam: e,
        isReset: false,
      },
      () => {
        if (this.state.checked) {
          //刷新
          this.getDatas(1, 10, e, this.state.selectVal);
          this.timer = setInterval(() => {
            this.getDatas(1, pageInfo?.numInPage ? pageInfo.numInPage : 10, e, this.state.selectVal);
          }, 5000);
        } else {
          //无刷新
          this.getDatas(1, pageInfo?.numInPage ? pageInfo.numInPage : 10, e, this.state.selectVal);
        }
      },
    );
  };
  //点击重置
  onClear = () => {
    this.setState({
      searchParam: { ...searchPars },
      isReset: true,
    });
  };
  //是否自动更新
  autoUpdate = (e) => {
    const { pageInfo } = this.props.proposalVerifyM;
    this.timer && clearInterval(this.timer);
    this.setState(
      {
        checked: e.target.checked,
      },
      () => {
        if (this.state.checked) {
          this.getDatas(pageInfo?.currentPage ? pageInfo.currentPage : 1, pageInfo?.numInPage ? pageInfo.numInPage : 10, this.state.searchParam, this.state.selectVal);
          //如果此时自动更新
          this.timer = setInterval(() => {
            this.getDatas(pageInfo?.currentPage ? pageInfo.currentPage : 1, pageInfo?.numInPage ? pageInfo.numInPage : 10, this.state.searchParam, this.state.selectVal);
          }, 5000);
        }
      },
    );
  };
  //改变表格列
  changeColumns = (columns) => {
    if (columns && columns.length) {
      // 最后一列添加操作列
      if (columns[columns.length - 1].title != '操作') {
        columns.push({
          title: '操作',
          dataIndex: 'operate',
          key: 'operate',
          type: 'operate',
          width: 100,
          operates: [
            {
              title: '审批',
              rules: {
                disabled: {
                  relation: 'and',
                  items: [{ key: 'proposalStatuss', value: ['NEW'], relation: ['!='] }],
                },
              },
              onClick: (record) => this.approvalProcess(record),
            },
          ],
        });
      }
      columns.map((item) => {
        if (item.key == 'proposalId') {
          item.width = 320;
        } else {
          item.width = 150;
        }
      });
    }
    return columns;
  };
  //表格列的审批点击
  approvalProcess = (record) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'proposalVerifyM/approveData',
      payload: {
        proposalId: record.proposalId,
      },
      callback: (res) => {
        if (res) {
          this.setState({
            modalVisible: true,
            rowObj: {
              id: record.proposalId,
              status: record.proposalStatuss,
            },
          });
        }
      },
    });
  };
  //表格改变事件
  onChange = (pagination) => {
    //点击重置的时候分页不可以直接点击，需要提示
    if (this.state.isReset) {
      message.warning('查询条件已重置，请重新查询！');
    } else {
      this.timer && clearInterval(this.timer);
      this.getDatas(pagination.current, pagination.pageSize, this.state.searchParam, this.state.selectVal);
      if (this.state.checked) {
        this.timer = setInterval(() => {
          this.getDatas(pagination.current, pagination.pageSize, this.state.searchParam, this.state.selectVal);
        }, 5000);
      }
    }
  };
  //处理建议书，状态下拉框的数据状态
  handleSelect = (ProposalStatus, ProposalType) => {
    //状态                     //建议书类型
    let proposalStatus_s = [];
    let proposalType_s = [];
    if (ProposalStatus) {
      ProposalStatus.map((item, index) => {
        proposalStatus_s.push({
          value: item.code,
          title: item.value,
          id: item.id,
        });
      });
    }
    if (ProposalType) {
      ProposalType.map((item, index) => {
        proposalType_s.push({
          value: item.code,
          title: item.value,
          id: item.id,
        });
      });
    }
    return {
      ProposalStatus_s: proposalStatus_s,
      ProposalType_s: proposalType_s,
    };
  };
  //此时是直接关闭的状态
  onCancels = () => {
    this.setState({
      modalVisible: false,
      loadingRefuse: false,
      loadingOk: false,
    });
  };
  onCancel = () => {
    //此时是关闭弹窗并且刷新的状态
    this.timer && clearInterval(this.timer);
    this.setState(
      {
        modalVisible: false,
        rowObj: null,
        loadingRefuse: false,
        loadingOk: false,
      },
      () => {
        if (this.state.checked) {
          this.getDatas(1, 10, this.state.searchParam, this.state.selectVal);
          this.timer = setInterval(() => {
            this.getDatas(1, 10, this.state.searchParam, this.state.selectVal);
          }, 5000);
        } else {
          this.getDatas(1, 10, this.state.searchParam, this.state.selectVal);
        }
      },
    );
  };
  handleOk = (proposalStatus) => {
    //此时是点击拒绝/通过按钮进行loading加载处理
    if (proposalStatus == 'NOT_APPROVED') {
      this.setState(
        {
          loadingRefuse: true,
          loadingOk: false,
        },
        () => {
          this.getAuth(proposalStatus);
        },
      );
    } else {
      this.setState(
        {
          loadingRefuse: false,
          loadingOk: true,
        },
        () => {
          this.getAuth(proposalStatus);
        },
      );
    }
  };
  getAuth = (proposalStatus) => {
    //点击拒绝、通过按钮后调用接口
    const {
      currentUser: { name },
    } = this.state;
    const { dispatch } = this.props;
    const { rowObj } = this.state;
    dispatch({
      type: 'proposalVerifyM/proposalAuth',
      payload: {
        proposalStatus,
        proposalId: rowObj.id,
        verifyUsername: name,
      },
      callback: () => {
        this.onCancel();
      },
    });
  };
  render() {
    const { columns, dataSource, pageInfo, loading, info, ProposalStatus, ProposalType } = this.props.proposalVerifyM;
    this.handleSelect(ProposalStatus, ProposalType);
    this.changeColumns(columns);
    return (
      <ContentPackage
        title='建议书审批'
        contentHtml={
          <div>
            <AdvancedSearch
              dataSource={[
                {
                  dataIndex: 'proposalWriteDate',
                  title: '日期',
                  type: DATA_ENTRY.SINGLEDATE,
                  initialValue: moment(new Date()),
                },
                {
                  dataIndex: 'proposalType',
                  title: '资产类型',
                  type: DATA_ENTRY.SELECT,
                  dataSource: [{ title: '场内(ETF)基金', value: 'ETF' }],
                  allowClear: true,
                  initialValue: 'ETF',
                },
                {
                  dataIndex: 'portfolioId',
                  title: '组合',
                  type: DATA_ENTRY.PRODUCTGROUPTREE,
                  maatApi: true,
                  tradeModel: ['BOOKKEEPING_MODE', 'COMMAND_MODE'], //不包含估值解析和估值对接的产品
                },
                {
                  dataIndex: 'proposalStatus',
                  title: '状态',
                  type: DATA_ENTRY.SELECT,
                  allowClear: true,
                  dataSource: this.handleSelect(ProposalStatus, ProposalType).ProposalStatus_s,
                },
                {
                  dataIndex: 'username',
                  title: '创建人',
                  type: DATA_ENTRY.INPUT,
                  allowClear: true,
                },
              ]}
              onQuery={this.onQuery}
              onClear={this.onClear}
            />
            <div>
              <Form.Item>
                <Checkbox checked={this.state.checked} onChange={this.autoUpdate}>
                  是否自动刷新
                </Checkbox>
              </Form.Item>
            </div>
            <div>
              <TableC
                columns={columns}
                dataSource={dataSource}
                total={pageInfo.total}
                pageSize={pageInfo.numInPage}
                current={pageInfo.currentPage}
                scroll={{ x: 'max-content' }}
                onChange={this.onChange}
                selfScrollY={true}
                loading={loading}
                rowKey='proposalId'
              />
            </div>
            <div>
              {this.state.modalVisible && (
                <ModalC
                  title='ETF建议书审批'
                  width={1036}
                  destroyOnClose={true}
                  onCancel={this.onCancels}
                  footer={
                    this.state.rowObj && this.state.rowObj.status == 'NEW'
                      ? [
                          <Button loading={this.state.loadingRefuse} key='reject' onClick={() => this.handleOk('NOT_APPROVED')}>
                            拒绝
                          </Button>,
                          <Button loading={this.state.loadingOk} key='ok' type='primary' onClick={() => this.handleOk('SENT')}>
                            通过
                          </Button>,
                        ]
                      : null
                  }
                  visible={this.state.modalVisible}
                >
                  <EtfProposalC onRef={(ref) => (this.child = ref)} type={4} proposalType={2} info={info}></EtfProposalC>
                </ModalC>
              )}
            </div>
          </div>
        }
      />
    );
  }
}
export default connect(({ etfOrderM, proposalVerifyM, userM: user, globalM }) => ({ etfOrderM, proposalVerifyM, user, globalM }))(ApprovalP);
